import React, {useEffect, useState, useRef, useLayoutEffect, useCallback} from 'react';
import {FlatList, View, Text, TouchableOpacity, Alert, StyleSheet, DeviceEventEmitter} from 'react-native';
import {LoadingView, Ticon, Spinner} from "react-native-gzdsx-elements";
import {defaultNavigationConfigure} from "../../../base/navconfig";
import {ButtonStyles, Colors, StatusBarStyles} from "../../../styles";
import {Button, ListItem} from "react-native-elements";
import {SafeFooter} from "../../../components/SafeView";
import ApiService from "../../../utils/ApiService";
import {useNavigation, useRoute} from "@react-navigation/native";
import StatusBarCtl from "../../../utils/StatusBarCtl";

const ActionButton = ({name, text, color = "#666", onPress = () => null}) => {
    return (
        <TouchableOpacity activeOpacity={1} onPress={onPress}>
            <View style={{flexDirection: 'row'}}>
                <Ticon name={name} size={20} color={color}/>
                <Text style={{
                    fontSize: 12,
                    color: '#333',
                    lineHeight: 20,
                    marginLeft: 3
                }}>{text}</Text>
            </View>
        </TouchableOpacity>
    );
};

const AddressItem = ({address, onPress, onSelect, onEdit, onDelete}) => {
    const route = useRoute();
    const navigation = useNavigation();

    return (
        <View style={{backgroundColor: '#fff'}}>
            <ListItem
                containerStyle={styles.addressContainer}
                onPress={() => {
                    onPress && onPress(address);
                }}
            >
                <ListItem.Content>
                    <View style={{flexDirection: 'row'}}>
                        <Text style={styles.addressName}>{address.name}</Text>
                        <Text style={styles.addressPhone}>{address.phone}</Text>
                    </View>
                    <Text style={styles.addressDetail} numberOfLines={2}>{address.formatted_address}</Text>
                </ListItem.Content>
            </ListItem>
            <ListItem>
                <ListItem.Content>
                    <ListItem.CheckBox
                        iconType={'octicon'}
                        checkedIcon={'check-circle-fill'}
                        uncheckedIcon={'circle'}
                        checkedColor={Colors.primary}
                        size={20}
                        title={'设为默认'}
                        textStyle={styles.checkBoxTitle}
                        containerStyle={styles.checkBoxContainer}
                        checked={address.isdefault === 1}
                        onPress={() => {
                            onSelect && onSelect(address);
                        }}
                    />
                </ListItem.Content>
                <View style={{justifyContent: 'center', flexDirection: 'row'}}>
                    <ActionButton name={"edit-light"} text={"编辑"} onPress={() => {
                        onEdit && onEdit(address);
                    }}/>
                    <View style={{width: 5}}/>
                    <ActionButton name={"delete-light"} text={"删除"} onPress={() => {
                        onDelete && onDelete(address);
                    }}/>
                </View>
            </ListItem>
        </View>
    );
}

export default function ({onChoose = () => null}) {
    const navigation = useNavigation();

    const [dataList, setDataList] = useState([]);
    const [loading, setLoading] = useState(true);
    const [refreshing, setRefreshing] = useState(false);

    useLayoutEffect(() => {
        navigation.setOptions({
            ...defaultNavigationConfigure(navigation),
            title: '管理收货地址',
        });

        return navigation.addListener('focus', () => {
            StatusBarCtl.setToDarkStyle();
        });
    }, [navigation])

    useEffect(() => {
        fetchData();
    }, []);

    useEffect(() => {
        if (refreshing) {
            fetchData();
        }
    }, [refreshing]);

    const fetchData = () => {
        ApiService.get('/user/addresses').then(response => {
            setDataList(response.result.items);
        }).catch(reason => {
            console.log(reason.message);
        }).finally(() => {
            Spinner.hide();
            setLoading(false);
            setRefreshing(false);
        });
    }

    const onDelete = useCallback(
        (id, index) => {
            Alert.alert(null, '确认要删除此地址吗?', [
                {
                    text: '取消', onPress: () => {
                    }
                },
                {
                    text: '确定',
                    onPress: () => {
                        ApiService.delete('/user/addresses/' + id).then(() => {
                            const newArr = dataList.splice(index, 1);
                            setDataList(newArr);
                        });
                    }
                }
            ]);
        },
        [dataList]
    )

    const onRefresh = () => {
        setRefreshing(true);
    }

    if (loading) return <LoadingView/>;
    return (
        <View style={{flex: 1}}>
            <FlatList
                data={dataList}
                renderItem={({item, index}) => (
                    <AddressItem
                        address={item}
                        onPress={address => {
                            onChoose && onChoose(address);
                        }}
                        onSelect={() => {
                            Spinner.show();
                            ApiService.put('/user/addresses/' + item.id, {address: {isdefault: 1}}).then(() => {
                                fetchData();
                            });
                        }}
                        onEdit={() => {
                            navigation.navigate('AddressEdit', {id: item.id});
                        }}
                        onDelete={() => {
                            onDelete(item.id, index)
                        }}
                    />
                )}
                keyExtractor={(item, index) => index.toString()}
                ItemSeparatorComponent={() => <View style={{height: 10}}/>}
                refreshing={refreshing}
                onRefresh={onRefresh}
            />
            <View style={{backgroundColor: '#fff'}}>
                <View style={{padding: 6}}>
                    <Button
                        title={'添加新地址'}
                        buttonStyle={ButtonStyles.primary}
                        onPress={() => {
                            navigation.navigate('AddressEdit', {});
                        }}
                    />
                </View>
                <SafeFooter/>
            </View>
        </View>
    );
}

const styles = StyleSheet.create({
    flexCenter: {},
    addressContainer: {
        borderBottomWidth: 0.5,
        borderBottomColor: '#f2f2ef',
        paddingVertical: 20
    },
    addressName: {
        fontSize: 16,
        color: '#333',
        marginRight: 10
    },
    addressPhone: {
        fontSize: 16, color: '#333'
    },
    addressDetail: {
        marginTop: 10,
        fontSize: 14,
        color: '#737373'
    },
    actionBar: {
        paddingVertical: 10
    },
    checkBoxTitle: {
        fontWeight: '400'
    },
    checkBoxContainer: {
        borderWidth: 0,
        backgroundColor: '#fff'
    }
})
